package cn.nubia.admin.api.jinshan.connect;

import cn.nubia.admin.api.jinshan.bean.CheckFile;
import cn.nubia.admin.api.jinshan.bean.CheckFileList;
import cn.nubia.admin.common.http.HttpClientReq;
import cn.nubia.admin.common.http.HttpRuntimeException;
import cn.nubia.admin.common.http.JsonUtil;
import org.codehaus.jackson.type.TypeReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 *  金山检测口
 * Created by wangj on 2015/7/23.
 */
public class CheckRequest {
    private final static Logger logger = LoggerFactory.getLogger(CheckRequest.class);

    private String queryAddress;
    /**
     * 版本
     */
    private  String version;
    /**
     * 合作方标示
     */
    private String tpl;
    /**
     * 签名秘钥
     */
    private String secureKey;

    private CheckFileList checkFileList;

    /**
     * 设置扫描文件列表
     * @param checkFileList
     */
    public void setCheckFiles(CheckFileList checkFileList) {
        this.checkFileList = checkFileList;
    }

    /**
     * 发送校验请求
     * @return
     */
    public boolean sendRequest() {
        HttpClientReq httpClientReq = HttpClientReq.build(toUrl());
        httpClientReq.addParam("request" , buildRequestUrl());
        try {
            CheckResp checkResp = httpClientReq.postForObject(new TypeReference<CheckResp>() {
            });
            if (logger.isInfoEnabled()) {
                logger.info("请求发送成功,返回信息为:{}" , checkResp.getErrorCode() );
            }
            Integer errorCode = checkResp.getErrorCode();
            if (errorCode == 0){
                return true;
            }else {
                return false;
            }
        }catch (HttpRuntimeException e) {
            logger.error("校验请求发送失败" , e);
        }
        return false;
    }

    private String buildRequestUrl() {
        if (checkFileList == null) {
            throw new RuntimeException("待检测文件列表不能为空");
        }

        return JsonUtil.toJson(checkFileList);
    }

    private String toUrl() {
        StringBuilder sb = new StringBuilder();
        sb.append(queryAddress).append("?").append("v=").append(version).append("&tpl=").append(tpl).append("&sign=").append(buildSign());
        return sb.toString();
    }

    /**
     * 将所有参数md5加密后做校验码传输
     * step1: 将所有输入参数（包括GET 和POST 参数，但除sign 参数外）格式化为"key=value"格式，
         如"k1=v1"、"k2=v2"、"k3=v3"；
         step2: 将格式化好的参数键值对以字典序升序方式排列后，拼接在一起，如"k1=v1k2=v2k3=v3"；
         step3: 在拼接好的字符串末尾拼接上我们为金山提供的secure_key，并对获取到的字符串算MD5
         签名，签名值即为sign 参数的值。
     * @return
     */
    private String buildSign() {
        StringBuilder sb = new StringBuilder();
        sb.append("v=").append(version).append("tpl=").append(tpl).append("request=" ).append(buildRequestUrl()).append("secure_key").append(secureKey);
        return "";
    }

    public void setVersion(String version) {
        this.version = version;
    }

    public void setTpl(String tpl) {
        this.tpl = tpl;
    }

    public void setSecureKey(String secureKey) {
        this.secureKey = secureKey;
    }


    public void setQueryAddress(String queryAddress) {
        this.queryAddress = queryAddress;
    }

    public String getSecureKey() {
        return secureKey;
    }
}
